package com.lai.berry_core.app;

import com.joanzapata.iconify.IconFontDescriptor;
import com.joanzapata.iconify.Iconify;

import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Interceptor;

public class Configurator {
    /**
     * 存放配置
     */
    private static final HashMap<Object, Object> BERRY_CONFIGS = new HashMap<>();

    private static final ArrayList<IconFontDescriptor> ICONS=new ArrayList<>();
    private static final ArrayList<Interceptor> INTERCEPTORS=new ArrayList<>();

    private Configurator() {
        BERRY_CONFIGS.put(ConfigKeys.CONFIG_READY, false);//配置开始，标记为未初始化完成


    }

    public static Configurator getInstance() {
        return Holder.INSTANCE;
    }

    /**
     * 获取所有的配置
     * @return
     */
    final HashMap<Object, Object> getBerryConfigs() {
        return BERRY_CONFIGS;
    }

    /**
     * 静态内部类单例
     */
    private static class Holder {

        private static final Configurator INSTANCE = new Configurator();
    }

    /**
     * 配置完成
     */
    public final void  configure(){
        initIconify();
        BERRY_CONFIGS.put(ConfigKeys.CONFIG_READY, true);//配置完成了
    }

    /**
     * 增加图标
     * @param descriptor
     * @return
     */
    public final Configurator withIcon(IconFontDescriptor descriptor){
        ICONS.add(descriptor);
        return this;
    }

    /**
     * 初始化图标
     */
    private  void initIconify(){
        if (ICONS.size()>0){
            final Iconify.IconifyInitializer initializer=Iconify.with(ICONS.get(0));
            for (int i=1;i<ICONS.size();i++){
                initializer.with(ICONS.get(i));
            }
        }
    }
    /**
     * 配置项
     * @param host
     * @return
     */
    public final Configurator withApiHost(String host){
        BERRY_CONFIGS.put(ConfigKeys.API_HOST,host);
        return this;
    }

    /**
     * 检查是否配置完成
     */
    private void checkConfiguration(){
        final boolean isReady= (boolean) BERRY_CONFIGS.get(ConfigKeys.CONFIG_READY);
        if (!isReady){
            throw new RuntimeException("configuration is not ready,call configure");
        }
    }

    /**
     * 获取某项配置
     * @param key
     * @param <T>
     * @return
     */
    final <T> T getConfiguration(Object key){
        checkConfiguration();//获取前检查是否配置完成
        return (T) BERRY_CONFIGS.get(key);
    }

    public final Configurator widthInterceptor(Interceptor interceptor){
        INTERCEPTORS.add(interceptor);
        BERRY_CONFIGS.put(ConfigKeys.INTERCEPTOR,INTERCEPTORS);
        return this;
    }

    public final Configurator widthInterceptors(ArrayList<Interceptor> interceptors){
        INTERCEPTORS.addAll(interceptors);
        BERRY_CONFIGS.put(ConfigKeys.INTERCEPTOR,INTERCEPTORS);
        return this;
    }



}
